package com.ow.dva.module.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.ow.dva.config.ShopInfo;
import com.ow.dva.module.base.entity.json.RT;
import com.ow.dva.module.base.entity.param.DvaPage;
import com.ow.dva.module.base.service.impl.DvaServiceImpl;
import com.ow.dva.module.front.entity.Fold;
import com.ow.dva.module.order.entity.Order;
import com.ow.dva.module.order.mapper.OrderMapper;
import com.ow.dva.module.order.service.OrderService;
import com.ow.dva.module.park.entity.JsonAccount;
import com.ow.dva.module.serverSettings.service.ServerSettingsService;
import com.ow.dva.util.jpush.JiguangPush;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author YanZengBao
 * @version V1.0
 * @since 2020-02-19
 */
@Service
public class OrderServiceImpl extends DvaServiceImpl<OrderMapper, Order> implements OrderService {


    @Override
    public DvaPage<Order> page(DvaPage<Order> page, Map<String, Object> param) {
        return baseMapper.page(page, param);
    }


    @Override
    public int getJsonOrder(String beanStr) {
        Order order = JSON.parseObject(beanStr, Order.class);
        if (order == null) return 0;
        int i = baseMapper.insert(order);
        if (i > 0) {
            //推送消息
            try {
                jpush(order, "1");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return i;
    }

    /**
     * 描述：支付成功推送信息
     * 创建时间：2020/4/26  YanZengBao
     * 修改时间：2020/4/26  YanZengBao 加注释
     * 修改时间：
     */
    public void jpush(Order order, String type) throws Exception {

        String alert = "";
        if ("1".equals(type)) {
            alert = "有新订单产生，请查看！";
        } else if ("2".equals(type)) {
            alert = "用户通过支付宝支付成功！";
        } else if ("3".equals(type)) {
            alert = "用户通过微信支付成功！";
        }

        if (order.getjPushStatus() != null && order.getjPushStatus() == 1) {
            RT rt = serverSettingsService.getDutyAccount(order.getRoadId());
            JsonAccount duty = JSON.parseObject(rt.getData().toString(), JsonAccount.class);
            if (duty != null) {
                //自定义携带的东西
                Map<String, String> map = new HashMap();
                map.put("type", type);
                map.put("orderId", order.getId());
                JSONObject jsonObject = JSONObject.fromObject(map);
                String jsonStr = jsonObject.toString();
                JiguangPush.jpush(duty.getAccountInfoId(), alert, jsonStr, type);
            } else {
                System.out.println("没有值班人！");
            }
        }
    }

    @Override
    public String uniformOrder(String orderId) throws AlipayApiException {
        System.out.println("--------------------支付宝扫描支付统一下单中-------------------------");
        AlipayClient alipayClient = new DefaultAlipayClient(ShopInfo.HTTPURL,ShopInfo.APPId,ShopInfo.PRIVATEKEY,ShopInfo.FORMAT,ShopInfo.CHARSET,ShopInfo.ALIPAYPUBLICKEY,ShopInfo.signType);
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
//        String out_trade_no =orderId+"_"+ (int)(Math.random()*100) ;
        Order order = getById(orderId);
        if(order ==null){
            return "未获取到订单";
        }
//       double totalFee = order.getReallyMoney();//正式上线后
        double totalFee = 0.01;//测试
        String out_trade_no =orderId ;
        String subject ="停车场支付";
        String param ="{" +
                "\"out_trade_no\":\""+out_trade_no+"\","+
                "\"total_amount\":"+totalFee+","+
                "\"subject\":\""+subject+"\""+
                "  }";
        request.setBizContent(param);
        request.setNotifyUrl(ShopInfo.CALLBACKURL); //回调路径
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            String qrCode = response.getQrCode();
            System.out.println(qrCode);
            return qrCode;
        }else{
            return "支付宝下单失败";
        }
    }

    @Override
    public List<Fold> countOrderByPark(String parkId) {
        List<Fold> foldList = new ArrayList<>();
        Date now = new Date();
        long nowTime = now.getTime();
        for (int i=6 ; i>=0 ;i--){
            SimpleDateFormat outFormat = new SimpleDateFormat("MM-dd");
            long time = nowTime - 86400000 * i;
            Date rDate = new Date(time);
            long count = baseMapper.countOrderByPark(parkId,rDate);
            Fold fold = new Fold();
            fold.setValue(String.valueOf(count));
            String axi = outFormat.format(rDate);
            fold.setAxis(axi);
            foldList.add(fold);
        }

        return foldList;
    }

    @Override
    public List<Order> sevenDayOrdersByPark(Map map) {
        return baseMapper.sevenDayOrdersByPark(map);
    }

    /**
     * 探知扫描设备是支付宝还是微信
     * @param request
     * @return
     */
    @Override
    public RT isWxOrAli(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent");
        if (userAgent != null && userAgent.contains("AlipayClient")){
            return RT.ok("1","支付宝");
        }else if (userAgent != null && userAgent.contains("MicroMessenger")){
            return RT.ok("2","微信");
        }else {
            return RT.ok("3","未知来源");
        }
    }

    @Override
    public List<Order> selectByplateNo(Map map) {
        return baseMapper.selectByplateNo(map);
    }

    @Override
    public Order selectNewOrderByRoad(String id) {
        return baseMapper.selectNewOrderByRoad(id);
    }

    @Override
    public List<Order> selectOrderListByRoad(String roadId) {
        return baseMapper.selectOrderListByRoad(roadId);
    }

    @Override
    public List<Order> selectByParkId(String parkId) {
        return baseMapper.selectByParkId(parkId);
    }

    @Override
    public List<Order> getAllTodayOrders() {
        return baseMapper.getAllTodayOrders();
    }

    @Override
    public List<Order> getAllTodayOrdersByParkId(String parkId) {
        return baseMapper.getAllTodayOrdersByParkId(parkId);
    }

    @Override
    public List<Order> getAllTodayOrders1() {
        return baseMapper.getAllTodayOrders1();
    }

    @Override
    public List<Order> getAllTodayOrdersByParkId1(String parkId) {
        return baseMapper.getAllTodayOrdersByParkId1(parkId);
    }

    @Override
    public List<Order> someDayOrdersByPark(Map map) {
        return baseMapper.someDayOrdersByPark(map);
    }

    @Override
    public List<Order> someDayOrders(Map map) {
        return baseMapper.someDayOrders(map);
    }

    @Override
    public List<Order> halfMonthOrdersByPark(Map map) {
        return baseMapper.halfMonthOrdersByPark(map);
    }

    @Override
    public List<Order> halfMonthOrders(Map map) {
        return baseMapper.halfMonthOrders(map);
    }

    @Override
    public List<Order> oneMonthOrdersByPark(Map map) {
        return baseMapper.oneMonthOrdersByPark(map);
    }

    @Override
    public List<Order> oneMonthOrders(Map map) {
        return baseMapper.oneMonthOrders(map);
    }

    @Override
    public List<Order> oneYearOrdersByPark(Map map) {
        return baseMapper.oneYearOrdersByPark(map);
    }

    @Override
    public List<Order> oneYearOrders(Map map) {
        return baseMapper.oneYearOrders(map);
    }

    @Resource
    private ServerSettingsService serverSettingsService;
}
